﻿using System.Reflection;
using System.Collections.Generic;
using UnityEngine;

//------------------------------------------------------------
// shaco Framework
// Copyright © 2017-2025 chang.liu All rights reserved.
// Feedback: 449612236@qq.com
//------------------------------------------------------------

namespace shaco
{
    /// <summary>
    /// 默认的UI显示深度变化方法，以UGUI为准
    /// </summary>
    public class DefaultUIDepthChange : IUIDepthChange
    {
        private class DepthData
        {
            public UnityEngine.UI.GraphicRaycaster graphicRaycaster = null;
            public UnityEngine.Canvas canvas = null; 
        }

        public void ChangeDepthAsTopDisplay(IUIRootComponent uiRoot, IUIState state)
        {
            var currentParentNode = state.parent.transform;

            //设置渲染到最高层
            currentParentNode.SetAsLastSibling();

            //TIPS: 2025/02/10 不能盲目增加Canvas数量，而是应该动静分离，只对经常需要变化的UI添加Canvas
            // //刷新同一父节点下的所有UI对象的cavans层级
            // var uiRootCompnent = uiRoot as Component;
            // if (null != uiRootCompnent && uiRootCompnent.transform.childCount > 0)
            // {
            //     for (int i = uiRootCompnent.transform.childCount - 1; i >= 0; --i)
            //     {
            //         var otherParentNode = uiRootCompnent.transform.GetChild(i).gameObject;
            //         var canvasFind = otherParentNode.GetComponent<UnityEngine.Canvas>();
            //         if (null == canvasFind)
            //         {
            //             otherParentNode.GetOrAddComponent<UnityEngine.UI.GraphicRaycaster>();
            //             canvasFind = otherParentNode.GetOrAddComponent<UnityEngine.Canvas>();
            //             canvasFind.overrideSorting = true;
            //             canvasFind.sortingLayerName = LayerMask.LayerToName(uiRootCompnent.gameObject.layer);
            //         }
            //         canvasFind.sortingOrder = (uiRoot.layerIndex * 100) + i;
            //     }
            // }
        }

        public IUIState GetTopUI(IUIRootComponent uiRoot, System.Func<IUIState, bool> conditionCallBack = null)
        {
            IUIState retValue = null;
            var uiRootCompnent = uiRoot as Component;
            for (int i = uiRootCompnent.transform.childCount - 1; i >= 0; --i)
            {
                var uiStateTarget = uiRootCompnent.transform.GetChild(i);
                var uiState = uiStateTarget.GetComponent<IUIState>();
                if (null != uiState && (null == conditionCallBack || conditionCallBack(uiState)))
                {
                    retValue = uiState;
                    break;
                }
            }
            return retValue;

        }
    }
}